package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        R<Employee> r = employeeService.login(employee);
        if(r.getCode()==1){
            session.setAttribute("employee",r.getData().getId());
        }
        return r;
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        long empId = (long)session.getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employeeService.save(employee);

        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(int page,int pageSize,String name){
        Page<Employee> resPage = employeeService.selectByPage(page, pageSize, name);
        return R.success(resPage);
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        R<Employee> r = employeeService.findById(id);
        return r;
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        long empId = (long)session.getAttribute("employee");
        employee.setUpdateUser(empId);
        employeeService.update(employee);
        return R.success("修改成功");
    }
}
